package com.example.basic01;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class EscapeGC {

    public static EscapeGC SAVE_HOOK = null;

    public void isAlive() {
        log.info("yes,I am Still alive.");
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        log.info("finalize method executed.");
        EscapeGC.SAVE_HOOK = this;
    }

    public static void main(String[] args) throws InterruptedException {
        SAVE_HOOK = new EscapeGC();
        SAVE_HOOK = null;
        System.gc();
        // // 因为Finalizer方法优先级很低，暂停0.5秒，以等待它
        Thread.sleep(500);
        if (SAVE_HOOK != null) {
            SAVE_HOOK.isAlive();
        } else {
            log.info("I am dead.");
        }
        SAVE_HOOK = null;
        System.gc();
        // 因为Finalizer方法优先级很低，暂停0.5秒，以等待它
        Thread.sleep(500);
        if (SAVE_HOOK != null) {
            SAVE_HOOK.isAlive();
        } else {
            log.info("no, i am dead :(");
        }
    }
}
